import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import { useInitialState } from '@/utils/use-initial-state'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { Dispatch } from 'redux'
import { logout } from '@/store/actions/login'

import {
  getUserProfile,
  updateProfile,
  updatePhoto,
} from '@/store/actions/profile'

import EditInput from './components/EditInput'
import EditList from './components/EditList'

import classNames from 'classnames'
import dayjs from 'dayjs'

import styles from './index.module.scss'

type IptPopup = {
  type: '' | 'name' | 'intro'
  value: string
  visible: boolean
}
type ListPopup = {
  type: '' | 'gender' | 'photo'
  visible: boolean
}

const ProfileEdit = () => {
  const history = useHistory()
  const fileRef = useRef<HTMLInputElement>(null)
  const dispatch = useDispatch<Dispatch<any>>()

  const [iptVisible, setIptVisible] = useState<IptPopup>({
    type: '',
    value: '',
    visible: false,
  })

  const [listPopup, setListPopup] = useState<ListPopup>({
    type: '',
    visible: false,
  })

  const [showData, setShowData] = useState(false)

  const { userProfile } = useInitialState(getUserProfile, 'profile')

  const { birthday, gender, id, name, photo, intro } = userProfile

  const onLogout = () => {
    Dialog.show({
      title: '温馨提示',
      content: '亲, 您确定要退出吗?',
      closeOnAction: true,
      closeOnMaskClick: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            style: {
              color: '#999',
            },
          },
          {
            key: 'confirm',
            text: '确认',
            onClick: () => {
              dispatch(logout())
              history.replace('/login')
            },
          },
        ],
      ],
    })
  }

  const onUpdateBirthDay = (value: Date) => {
    const formatBirthday = dayjs(value).format('YYYY-MM-DD')
    onUpdateProfile('birthday', formatBirthday)
  }

  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.dir(e.target.files)
    if (!e.target.files) {
      Toast.show({
        content: '请选择要上传的头像',
        duration: 1000,
      })
      return
    }
    const formData = new FormData()
    formData.append('photo', e.target.files[0])

    await dispatch(updatePhoto(formData))

    onListClose()

    Toast.show({
      content: '头像上传成功',
      duration: 500,
    })
  }

  const onUpdateProfile = async (
    type: 'name' | 'intro' | 'gender' | 'photo' | 'birthday',
    name: string
  ) => {
    if (type === 'photo') {
      fileRef.current?.click()
    } else {
      await dispatch(updateProfile({ [type]: name }))

      Toast.show({
        content: '更新成功',
        duration: 800,
      })
      onClose()
      onListClose()
    }
  }

  const onListShow = (type: ListPopup['type']) => {
    setListPopup({
      type,
      visible: true,
    })
  }
  const onListClose = () => {
    setListPopup({
      type: '',
      visible: false,
    })
  }
  const onOpen = (type: IptPopup['type'], value: IptPopup['value']) => {
    setIptVisible({
      type,
      value,
      visible: true,
    })
  }

  const onClose = () => {
    setIptVisible({
      type: '',
      value: '',
      visible: false,
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.go(-1)}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <List.Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow
              onClick={() => onListShow('photo')}
            >
              头像
            </List.Item>
            <List.Item arrow extra={name} onClick={() => onOpen('name', name)}>
              昵称
            </List.Item>
            <List.Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {intro ?? '未填写'}
                </span>
              }
              onClick={() => onOpen('intro', intro ?? '')}
            >
              简介
            </List.Item>
          </List>

          <List className="profile-list">
            <List.Item
              arrow
              extra={gender + '' === '0' ? '男' : '女'}
              onClick={() => onListShow('gender')}
            >
              性别
            </List.Item>
            <List.Item arrow extra={birthday} onClick={() => setShowData(true)}>
              生日
            </List.Item>
          </List>

          <DatePicker
            title="选择年月日"
            value={new Date(birthday)}
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            visible={showData}
            onClose={() => setShowData(false)}
            onConfirm={onUpdateBirthDay}
          />
          <input
            ref={fileRef}
            type="file"
            style={{ display: 'none' }}
            onChange={onChangePhoto}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>
            退出登录
          </Button>
        </div>
      </div>

      <Popup
        visible={iptVisible.visible}
        position="right"
        bodyStyle={{ minWidth: '60vw' }}
        destroyOnClose // 第二种解决无法正常显示简介的情况
      >
        <EditInput
          key={iptVisible.type} // 第三种解决无法正常显示简介的情况
          type={iptVisible.type}
          value={iptVisible.value}
          onClose={onClose}
          onUpdateProfile={onUpdateProfile}
        ></EditInput>
      </Popup>

      <Popup visible={listPopup.visible} onMaskClick={onListClose}>
        <EditList
          type={listPopup.type}
          onUpdateProfile={onUpdateProfile}
          onClose={onListClose}
        ></EditList>
      </Popup>
    </div>
  )
}

export default ProfileEdit
